import React from "react";
import ReactDOM from "react-dom";
import {Select, Tooltip} from "antd";
import BaseComponent from "../../../redare/components/BaseComponent";

import BaseAreaPresenter from "../../../.gen/presenter/BaseAreaPresenter";
import {saveStorage,getStorage} from "../../../common/StorageUtils";

/**
 * 籍贯地区选择
 */
export default class AreaSelectForNativePlace extends BaseComponent {

    // 是否使用浏览器缓存策略
    isBrowseCachePlan = true;
    // 浏览器缓存Key前缀
    browseCacheKeyPrefix = "areaList";
    // 地区数据
    areaData={
        provinceCode: null,
        province: null,
        cityCode: null,
        city: null
    };


    constructor(props) {
        super(props);
        this.baseAreaPresenter = new BaseAreaPresenter(this);

        if( this.props.isBrowseCachePlan == false ){
            this.isBrowseCachePlan = this.props.isBrowseCachePlan;
        }

        this.state = {
            provinceLoading: false,
            cityLoading: false,
            cityOpen: false,
            districtLoading: false,
            districtOpen:false,
            provinceData: [],
            cityData: [],
            districtData: [],
            provinceValue: null,
            cityValue: null,
            districtValue: null
        }
    }

    componentDidMount() {
        // 默认只加载省
        this._loadProvinceData('CN');
        this.addListenEvent();
    }


    resetFields() {
        this.setState({
            provinceValue: null,
            cityValue: null,
            districtValue: null
        })
    }

    /**
     * 组件对外获取数据的函数
     * @param separator 字符串地址分隔符号
     * @returns
     */
    getData(separator){
        if( !separator ){
            separator = '';
        }
        let data = {...this.areaData};

        let areaStr =  data.province;

        if( !data.province ){
            return null;
        }

        if(  data.city ){
            areaStr += separator + data.city;
        }

        data.areaStr = areaStr;

        return data;
    }

    // 对组件进行赋值
    setData(data){

        if( !data ){
            return ;
        }

        let areaData={
            provinceCode: data.provinceCode,
            province: data.province,
            cityCode: data.cityCode,
            city: data.city,
            areaStr: data.areaStr
        };


        this.areaData = areaData;

        if( data.provinceCode ){
            this._loadCityData(data.provinceCode, true);
        }

        this.setState({
            provinceValue: data.provinceCode,
            cityValue: data.cityCode
        });

    }


    // 默认使用浏览器缓存方式获取数据
    _loadData(parentCode, callbackFn){

        let continueLoadServerData = false;

        if( this.isBrowseCachePlan ){
            let data = getStorage(this.browseCacheKeyPrefix+"_"+parentCode);
            if( data == null){
                continueLoadServerData = true;
            }else{
                if( callbackFn && typeof callbackFn === 'function'){
                    callbackFn(data);
                }
                this.closeLoadingIndicator();
            }
        }else {
            continueLoadServerData = true;
        }

        if( continueLoadServerData ){
            this.__loadData(parentCode, callbackFn);
        }

    }

    // 核心请求服务接口后加载数据
    __loadData(parentCode, callbackFn){
        this.baseAreaPresenter.findAreaListByParentCode(
          {parentCode},
          {},
          (s_r)=>{
              let data = s_r.data;
              if (this.isBrowseCachePlan) {
                  saveStorage(this.browseCacheKeyPrefix+"_"+parentCode, data);
              }
              if( callbackFn && typeof callbackFn === 'function'){
                  callbackFn(data);
              }
          },
          (f_r)=>{

          }
        );
    }

    // 加载省数据
    _loadProvinceData(parentCode){
        this.setState({provinceLoading: true});
        this._loadData(parentCode, (data)=>{

            this.setState({provinceData: data});
        });
    }

    // 加载市数据
    _loadCityData(parentCode, silently){
        this.setState({
            cityLoading: true,
            provinceValue: parentCode,
            cityValue: null,
        });
        this._loadData(parentCode, (data)=>{
            this.setState({cityData: data});
            if( !silently && data && data.length > 0 ){
                // 使市获取的焦点
                if( this.citySelect ){
                    this.citySelect.focus();
                }
                this.setState({cityOpen: true});
            }
        });
    }


    getOption(data){
        let options = [];
        if( !data || data.length === 0){
            return options;
        }
        data.map((item)=>{
            options.push(
              <Select.Option key={item.areaCode} value={item.areaCode} data={item}>
                  <Tooltip title={item.areaName}>{item.areaName}</Tooltip>
              </Select.Option>
            );
        });
        return  options;
    }


    // 组装下拉数据
    _selectData(option, type){
        let data = option.data;
        this.areaData[type+"Code"] = data.areaCode;
        this.areaData[type] = data.areaName;
    }

    render() {

        let state = this.state;

        let selectAttr = {
            showSearch:true,
            optionFilterProp:"children",
            getPopupContainer: triggerNode => triggerNode.parentElement,
            onBlur: ()=>{
                this.setState({districtOpen: false, cityOpen: false});
            },
            filterOption: (inputValue,option)=>{
                if( option.data["areaName"].indexOf(inputValue) > -1 ){
                    return true;
                }
                return false;
            }
        };


        return (

          <div className={'flex-son-margin5'} ref={(o)=>{this.selectGroup = o}}>
              <Select
                {...selectAttr}
                loading={state.provinceLoading}
                placeholder={"省"}
                value={state.provinceValue}
                onSelect={(value,option)=>{
                    this._selectData(option, 'province');
                    this._loadCityData(value);
                }}
              >
                  {this.getOption( state.provinceData )}
              </Select>
              <Select
                {...selectAttr}
                ref={(the)=>{this.citySelect = the}}
                loading={state.cityLoading}
                placeholder={"市"}
                value={state.cityValue}
                open={state.cityOpen}
                onSelect={(value,option)=>{
                    this._selectData(option, 'city');
                    this.setState({cityValue: value, cityOpen: false});

                    //此方法只是为了触此组件被 Form.Item 包裹时的验证
                    if(this.props.onChange && this.props.onChange.constructor === Function){
                        this.props.onChange({});
                    }
                }}
              >
                  {this.getOption( state.cityData )}
              </Select>
          </div>


        );
    }


    closeLoadingIndicator(){
        this.setState({
            provinceLoading: false,
            cityLoading: false,
            districtLoading: false
        });
    }

    addListenEvent(){

        // 不使用焦点因为第二次焦点本身就存在了焦点，所以第二次将无法展开
        let citySelect = ReactDOM.findDOMNode(this.citySelect);

        let cityInput = citySelect.querySelector(".ant-select-selector");
        cityInput.addEventListener("click",  ()=> {
            this.setState({cityOpen: true});
        });

    }

}
